<?php

namespace App\Services;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;

class DingTalkService
{
    protected $client;
    protected $appKey;
    protected $appSecret;
    protected $corpId;

    public function __construct()
    {

        // $this->client = new Client();
        $this->client = new Client(
            [
                'verify' => false,
            ]
        );
        $this->appKey = env('DINGTALK_APP_KEY');
        $this->appSecret = env('DINGTALK_APP_SECRET');
        $this->corpId = env('DINGTALK_CORP_ID');
    }

    /**
     * 获取AccessToken,token的有效时长是7200秒，过期前需要重新获取，remember方法缓存的单位是分钟，需要将7200秒除以60
     */
    public function getAccessToken()
    {
        return Cache::remember('dingtalk:access_token', 7000 / 60, function () {
            $url = "https://oapi.dingtalk.com/gettoken?appkey={$this->appKey}&appsecret={$this->appSecret}";

            try {
                $response = $this->client->get($url);
                $data = json_decode($response->getBody(), true);

                if ($data['errcode'] !== 0) {
                    throw new \Exception("获取AccessToken失败: {$data['errmsg']}");
                }

                return $data['access_token'];
            } catch (\Exception $e) {
                throw new \Exception("获取AccessToken异常: " . $e->getMessage());
            }
        });
    }

    /**
     * 根据authCode获取用户信息
     */
    public function getUserInfoByCode($authCode)
    {
        $accessToken = $this->getAccessToken();
        $url = "https://oapi.dingtalk.com/user/getuserinfo?access_token={$accessToken}&code={$authCode}";

        try {
            $response = $this->client->get($url);
            $data = json_decode($response->getBody(), true);

            if ($data['errcode'] !== 0) {
                throw new \Exception("获取用户信息失败: {$data['errmsg']}");
            }

            return $this->getUserDetail($data['userid']);
        } catch (\Exception $e) {
            throw new \Exception("获取用户信息异常: " . $e->getMessage());
        }
    }

    /**
     * 获取用户详情
     */
    protected function getUserDetail($userId)
    {
        $accessToken = $this->getAccessToken();
        $url = "https://oapi.dingtalk.com/user/get?access_token={$accessToken}&userid={$userId}";

        try {
            $response = $this->client->get($url);
            $data = json_decode($response->getBody(), true);

            if ($data['errcode'] !== 0) {
                throw new \Exception("获取用户详情失败: {$data['errmsg']}");
            }

            return $data;
        } catch (\Exception $e) {
            throw new \Exception("获取用户详情异常: " . $e->getMessage());
        }
    }

    /**
     * 获取企业CorpId
     */
    public function getCorpId()
    {
        return $this->corpId;
    }
}
